package com.ukit.weather_xml

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import android.widget.EditText
import androidx.fragment.app.DialogFragment
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

class InputCityDialog: DialogFragment() {
    @SuppressLint("MissingInflatedId")
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val builder = AlertDialog.Builder(activity)
        val inflater = requireActivity().layoutInflater
        val view = inflater.inflate(R.layout.dialog_input_city, null)
        val editText = view.findViewById<EditText>(R.id.editTextNewItem)

        builder.setView(view)
            .setTitle("Введите город")
            .setPositiveButton("Ок",
                DialogInterface.OnClickListener { dialog, id ->
                    GlobalScope.launch(Dispatchers.Main) {
                        val newItemText = editText.text.toString()
                        val mainActivity = activity as MainActivity
                        mainActivity.changeCity(newItemText)
                    }

                })
            .setNegativeButton("Отмена",
                DialogInterface.OnClickListener { dialog, id ->
                    dialog.cancel()
                })
        return builder.create()
    }
}
